from .models import User
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler
from recruitment.serializers import EnterpriseSimpleModelserializer
from question.models import Label
from headlines.models import Article


class UserSerializer(serializers.ModelSerializer):

    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile',
                    'token', 'avatar', 'sms_code']
        extra_kwargs = {
            'model': {'min_length': 11},
            'username': {'min_length': 3},
            'password': {'min_length': 6, 'max_length': 16},
        }

    def validate(self, attrs):

        sms_code = attrs['sms_code']
        mobile = attrs['mobile']

        redis_conn = get_redis_connection('verify_code')

        redis_sms_code = redis_conn.get('sms_%s' % mobile)

        if redis_sms_code == None:
            raise serializers.ValidationError('验证码过期')

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs


    def create(self, validated_data):

        validated_data.pop('sms_code')

        user = User.objects.create_user(**validated_data)

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user


class ArticleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'



class LabelModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = [
            'id',
            'label_name'
        ]


# 用户详细信息
class UserInfoModelSerializer(serializers.ModelSerializer):
    labels = LabelModelSerializer(many=True)
    questions = serializers.StringRelatedField(many=True)
    replies = serializers.StringRelatedField(many=True)
    collected_articles = ArticleModelSerializer(many=True)
    enterpises = EnterpriseSimpleModelserializer(many=True)
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'realname',
            'birthday',
            'sex',
            'avatar',
            'website',
            'email',
            'city',
            'address',
            'labels', # 外键字段
            'questions', # 外键字段
            'replies', # 外键字段
            'collected_articles', # 外键字段
            'enterpises', # 外键字段
        ]

        # extra_kwargs = {
        #     'password': {'write_only': True}
        # }